package com.bree.erp.service.stateless;

import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.bree.erp.entity.BalanceId;
import com.bree.erp.entity.PartUnit;
import com.bree.erp.entity.ReturnsBalance;
import com.bree.erp.entity.Warehouse;
import com.bree.erp.service.ReturnsBalanceService;

@Stateless
public class ReturnsBalanceServiceBean implements ReturnsBalanceService {

	@PersistenceContext()
	private EntityManager em;
	
	public ReturnsBalanceServiceBean() {
		
	}

	public ReturnsBalanceServiceBean(EntityManager em) {
		this.em = em;
	}

	@Override
	public ReturnsBalance create(String warehouseId, Long partUnitId) {
		
		Warehouse warehouse = em.find(Warehouse.class, warehouseId);
		PartUnit partUnit = em.find(PartUnit.class, partUnitId);
		
		ReturnsBalance entity = new ReturnsBalance();
		
		entity.setWarehouse(warehouse);
		entity.setPartUnit(partUnit);
		
		em.persist(entity);
		return entity;
	}

	@Override
	public ReturnsBalance read(BalanceId id) {
		
		return em.find(ReturnsBalance.class, id);
	}

	@Override
	public ReturnsBalance update(BalanceId id, double adjustment) {
		
		ReturnsBalance entity = read(id);
		double totalBalance = entity.getTotalBalance() + adjustment;
		entity.setTotalBalance(totalBalance);
		
		entity.setLastMovement(new Date());
		
		return entity;
	}

	@Override
	public void delete(BalanceId id) {
		ReturnsBalance entity = read(id);
		
		em.remove(entity);
	}

	@Override
	public Collection<ReturnsBalance> list() {
		
		TypedQuery<ReturnsBalance> query = em.createNamedQuery(ReturnsBalance.QUERY_SELECT_ALL_BALANCE, ReturnsBalance.class);
		
		return query.getResultList();
	}

	@Override
	public List<ReturnsBalance> sumPartUnits() {

		TypedQuery<ReturnsBalance> query = em.createNamedQuery(ReturnsBalance.QUERY_SUM_ALL_BALANCE, ReturnsBalance.class);
		
		return query.getResultList();
	}
}
